/*
 *
 * Copyright (c) 2020 The Raptor Authors. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "src/common/connection_id.h"

namespace raptor {

/* <5 bits><9 bits><18 bits>  */
/* < magic><  id  >< index >  */

namespace internal {

uint32_t BuildConnectionId(uint16_t magic, uint16_t id, uint32_t index) {
    uint32_t c1 = index & 0x3ffff;
    uint32_t c2 = id & 0x1ff;
    uint32_t c3 = magic & 0x1f;

    return (c3 << 27) | (c2 << 18) | c1;
}

bool VerifyConnectionId(uint32_t cid, uint16_t magic) {
    uint32_t c3  = magic & 0x1f;
    uint32_t tmp = cid >> 27;
    return tmp == c3;
}

uint16_t GetMagicNumber(uint32_t cid) { return static_cast<uint16_t>((cid >> 27) & 0x1f); }

uint16_t GetContainerId(uint32_t cid) { return static_cast<uint16_t>((cid >> 18) & 0x1ff); }

uint32_t GetConnectionIndex(uint32_t cid) { return static_cast<uint32_t>(cid & 0x3ffff); }
} // namespace internal

} // namespace raptor
